package com.woniu.demo.service.impl;

import com.woniu.demo.dao.StandardMapper;
import com.woniu.demo.exception.FileUploadException;
import com.woniu.demo.pojo.Standard;
import com.woniu.demo.service.StandardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 * @Description TODO
 * @date 2019/9/20
 */
@Service
public class StandardServiceImpl implements StandardService {

    @Autowired
    private StandardMapper standardMapper;

    @Override
    public List<Standard> findStandards(Integer currentPage, Integer pageSize, String condition) {
        return standardMapper.queryStandardsByPage(currentPage,pageSize,condition);
    }

    @Override
    public int removeBatch(Integer[] keys) {
        return standardMapper.deleteBatch(keys);
    }

    @Override
    public int addStandard(Standard standard, MultipartFile file,String path) {
        try {
            if(!file.isEmpty()){
                File upload  = new File(path);
                if(!upload.exists()){
                    upload.mkdirs();
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssS");
                String fileName = file.getOriginalFilename();
                String newFileName = sdf.format(new Date())+ fileName.substring(fileName.lastIndexOf("."));
                //文件归档 e:/upload/hello.jpg
                file.transferTo(new File(path+File.separator+newFileName));
                standard.setPackagepath(path+File.separator+newFileName);
            }
            standardMapper.insertSelective(standard);
            return 0;
        } catch (IOException e) {
            e.printStackTrace();
            throw new FileUploadException("文件上传失败");
        }
    }

    @Override
    public Standard findStandardById(Integer id) {
        return standardMapper.selectByPrimaryKey(id);
    }
}
